from pymysql import *
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
import sys
from PyQt5.QtChart import QChart, QChartView, QPieSeries, QPieSlice
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtCore import Qt

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.info = []   #记录从数据库获取的信息，每个元素是一个列表
        
        self.pNum = {}   #记录每个类型包的数量

        self.setWindowTitle("协议类型占比情况")
        self.setGeometry(100, 100, 1280, 600) #左右，上下，宽，高
    
        #self.show()
        
        self.ReadInfoFromDatabase()
        
        #print(self.info)

        #self.create_piechart()
        
    def ReadInfoFromDatabase(self):
        try:
            conn = connect(host='127.0.0.1', port=3306, user='root', password='020903chen..', db='protocol_infomation')
        except:
            print("读数据时连接失败！")
            
        cur = conn.cursor()
        
        tableName = "keyInfo"
            
        sql = ''' SELECT * FROM `%s`;''' %tableName
        cur.execute(sql)
        data3 = cur.fetchall()
        for d in data3:
            d = list(d)
            self.info.append(d)
            #print(d)

        conn.commit()
        cur.close()  # 关闭游标
        conn.close()  # 关闭数据库连接

    def create_piechart(self):
        series = QPieSeries()
        
        for keyInfo in self.info:
            if keyInfo[2] not in self.pNum.keys():
                self.pNum[keyInfo[2]] = 1
            else:
                self.pNum[keyInfo[2]] += 1
                
        #print(self.pNum)
        
        for pType in self.pNum:
            series.append(pType, self.pNum[pType])
        # series.append("Python", 1)
        # series.append("C++", 1)
        # series.append("Java", 1)
        # series.append("C#", 1)
        # series.append("PHP", 1)


        # adding slice
        for i in range(len(self.pNum)):
            slice = QPieSlice()
            slice = series.slices()[i]
            slice.setLabelVisible(True)

        chart = QChart()
        chart.legend().hide()
        chart.addSeries(series)
        chart.createDefaultAxes()
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.setTitle("协议类型占比情况统计")

        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignBottom)

        chartview = QChartView(chart)
        chartview.setRenderHint(QPainter.Antialiasing)

        self.setCentralWidget(chartview)
if __name__ == '__main__':
    App = QApplication(sys.argv)
    window = Window()
    window.show()
    window.create_piechart()
    sys.exit(App.exec_())
